/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useEffect } from 'react';
import { Form, DatePicker, TimePicker } from 'antd';
import moment from 'moment';
import { FormInstance } from 'antd/es/form/Form';

export interface IDate {
  format: string;
  value: string;
  form?: FormInstance<any>;
}

const Date: React.FC<IDate> = (props) => {
  let { value = '', format = '', form } = props;

  const valueStr = value?.split(' ')[1] ?? value!.split(' ')[0];
  const formatStr = format!.split(' ')[1] ?? format!.split(' ')[0];

  const isDateOnly = ['YYYY', 'DD', 'MM'].some((item) => format.includes(item));
  const isTimeOnly = ['HH', 'mm', 'ss'].some((item) => format.includes(item));

  useEffect(() => {
    if (value) {
      form?.setFieldsValue({
        date: moment(value.split(' ')[0], format.split(' ')[0]),
        time: moment(valueStr, formatStr),
      });
    }
  }, [value, valueStr, formatStr, format]);

  return (
    <>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <>
          {isDateOnly && (
            <Form.Item label="日期" name="date" rules={[{ required: true, message: '请选择日期' }]}>
              <DatePicker
                allowClear={false}
                style={{ width: '100%' }}
                format={format!.split(' ')[0]}
              />
            </Form.Item>
          )}
          {isTimeOnly && (
            <Form.Item label="时间" name="time" rules={[{ required: true, message: '请选择时间' }]}>
              <TimePicker allowClear={false} style={{ width: '100%' }} format={formatStr} />
            </Form.Item>
          )}
        </>
      </Form>
    </>
  );
};

export default Date;
